package tw.miku.thread;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class AttestationServer implements Runnable
{
	private ServerSocket server;
	private BufferedReader reader;
	private BufferedWriter writer;
	private static final String securityXml = "<?xml version='1.0'?>"
			+ "<cross-domain-policy> "
			+ "<allow-access-from domain='*' to-ports='*'/>"
			+ "</cross-domain-policy> ";

	public AttestationServer()
	{
		createServerSocket(843);
		new Thread(this).start();
	}

	private void createServerSocket(int port)
	{
		try
		{
			server = new ServerSocket(port);
		}
		catch (IOException e)
		{
			System.exit(0);
		}
	}

	@Override
	public void run()
	{
		while (true)
		{
			Socket client = null;
			try
			{
				client = server.accept();
				InputStreamReader input = new InputStreamReader(
						client.getInputStream(), "UTF-8");
				reader = new BufferedReader(input);
				OutputStreamWriter output = new OutputStreamWriter(
						client.getOutputStream(), "UTF-8");
				writer = new BufferedWriter(output);
				StringBuilder sb = new StringBuilder();
				int request = 0;
				while ((request = reader.read()) != -1)
				{
					if (request != '\0')
					{
						sb.append((char) request);
					}
					else
						break;
				}
				String message = sb.toString();
				if (message.indexOf("<policy-file-request/>") >= 0)
				{
					writer.write(securityXml + "\0");
					writer.flush();
				}
				client.close();
			}
			catch (Exception e)
			{
				e.printStackTrace();
				try
				{
					if (client != null)
					{
						client.close();
						client = null;
					}
				}
				catch (IOException ex)
				{
					ex.printStackTrace();
				}
				finally
				{
					System.gc();
				}
			}
		}
	}
}
